import { _decorator, Asset, AssetManager, assetManager, Component, instantiate, Node, physics, Prefab } from 'cc';
import { TouchEvent3D } from '../Tools/TouchEvent3D';
import { NailBase } from './Nail/NailBase';
import { TouchRotation3D } from '../Tools/TouchRotation3D';
const { ccclass, property } = _decorator;

@ccclass('GamePlay')
export class GamePlay extends Component {
    @property(TouchEvent3D)
    touchEvent3D: TouchEvent3D = null;

    @property(TouchRotation3D)
    touchRotation3D: TouchRotation3D = null

    @property(Node)
    map: Node = null

    protected onLoad(): void {
        if (!this.touchEvent3D)
            return console.error("touchEvent3D not find", this.touchEvent3D)
    }

    protected start(): void {
       this.addEvent()
       this.addLevel()
    }

    protected onDestroy(): void {
       this.offEvent()
    }


    private addEvent() {
        this.touchEvent3D.addEvent()
        this.touchEvent3D.onHit = this.onHit.bind(this)
        this.touchEvent3D.onNoHit = () => { console.log("未触摸3D物体") }


        this.touchRotation3D.addEvent()
    }

    private offEvent() {
        this.touchEvent3D.offEvent()
        this.touchEvent3D.onHit = null
        this.touchEvent3D.onNoHit = null


        this.touchRotation3D.offEvent()
    }

    private onHit(collider_: physics.Collider) {
        const touchNode_n = collider_.node
        const nail_com = touchNode_n.getComponent(NailBase)
        if (nail_com instanceof NailBase) {
            touchNode_n.getComponent(NailBase)
            nail_com.click()
        }
    }

    private addLevel() {
        assetManager.loadBundle("DaLuoSi",(err_: Error | null, bundle_: AssetManager.Bundle) => {
            if (err_) {
                return console.error(err_)
            }

            if (bundle_) {
                bundle_.load<Prefab>("LevelEditor/prefab/level/level1",(level_err_: Error | null, level_prefab_: Prefab) => {
                    if (level_err_) {
                        return console.error(level_err_)
                    }
                    if (level_prefab_) {
                        const level_node = instantiate(level_prefab_)
                        this.map.addChild(level_node)
                    }
                })
            }
        })
    }
}